package com.hl.toolkit.server.tycoin.account.slaveservice;

import com.alipay.demo.trade.ALIPayScan;
import com.bdpay.RefundServlet;
import com.tencent.WXPay;
import com.tencent.protocol.refund_protocol.RefundReqData;
import com.tenpay.other.demo.QQpayScann;
import com.tycoin.account.slaveentity.TycoinAccount;
import com.tycoin.account.slaveentity.TycoinAccountLog;
import com.tycoin.account.slaveentity.TycoinAccountRecharge;
import com.tycoin.account.slaveentity.TycoinEthLog;
import com.tycoin.account.slaverepository.TycoinAccountLogRepository;
import com.tycoin.account.slaverepository.TycoinAccountRepository;
import com.tycoin.account.slaverepository.TycoinEthLogRepository;
import com.tycoin.user.slaverepository.TycoinUserRepository;
import com.util.AmountUtil;
import com.util.DateUtils;
import com.util.XMLUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 充值回调过程数据处理
 * 
 * @author Administrator
 *
 */
@Service
@Transactional(value = "slaveTransactionManager")
public class TycoinAccountRechargeCallbackProcessService{

	
	
	@Autowired
	TycoinAccountRepository tycoinAccountRepository;
	@Autowired
	TycoinUserRepository tycoinUserRepository;
	@Autowired
	TycoinAccountLogRepository tycoinAccountLogRepository;
	@Autowired
	TycoinEthLogRepository tycoinEthLogRepository;

	@Autowired
	TycoinAccountRechargeService tycoinAccountRechargeService;

 
	public void rechargeCallbackProcess(TycoinAccountRecharge tycoinAccountRecharge) {
		String userId = String.valueOf(tycoinAccountRecharge.getUserId());
		String money = tycoinAccountRecharge.getMoneyfloat() + "";
		int pay_mode = tycoinAccountRecharge.getPayMode();

		String payMode = "";
		if (pay_mode == 1) {
			payMode = "微信支付";
		} else if (pay_mode == 2) {
			payMode = "支付宝";

		} else if (pay_mode == 3) {
			payMode = "百度钱包";
		} else if (pay_mode == 4) {
			payMode = "QQ钱包";
		} else if (pay_mode == 5) {
			payMode = "京东支付";
		} else if (pay_mode == 6) {
			payMode = "银联支付";
		}

		// 查询用户信息

		// 添加充值资金
		// --查询账户
		TycoinAccount outAccount = tycoinAccountRepository.findOneByuserId(userId);
		//老的金额
		String oldMoney = String.valueOf(outAccount.getUseEth());
		//新的金额
		Float newMoney=(AmountUtil.add(oldMoney, money)).floatValue();
		System.out.println("老的金额："+oldMoney+",新的金额："+newMoney+"");
		outAccount.setUseMoney(new BigDecimal(newMoney));
		tycoinAccountRepository.save(outAccount);
		// 1.添加打款方账积分账户日志记录
		long dateTime = System.currentTimeMillis();
		String tranNo = "CZ" + dateTime + (long) (Math.random() * 10000L);
		TycoinAccountLog tycoinAccountLog = new TycoinAccountLog();
		tycoinAccountLog.setUserId(String.valueOf(userId));
		tycoinAccountLog.setType("2");
		tycoinAccountLog.setTypeName("积分充值");
		tycoinAccountLog.setNum(Float.parseFloat(money));
		tycoinAccountLog.setRealNum(Float.parseFloat(money));
		tycoinAccountLog.setStatus(1);
		tycoinAccountLog.setRemark("[" + userId + "]使用了" + payMode + "进行了账户充值");
		tycoinAccountLog.setAddtime(System.currentTimeMillis());
		tycoinAccountLog.setTranNo(tranNo);
		tycoinAccountLog.setLogno(tycoinAccountRecharge.getLogno());
		tycoinAccountLogRepository.save(tycoinAccountLog);
		// 2.添加日志记录表
		TycoinEthLog tycoinEthLog = new TycoinEthLog();
		tycoinEthLog.setUserId(String.valueOf(userId));
		tycoinEthLog.setOldNum(Float.parseFloat(oldMoney));
		tycoinEthLog.setNum(Float.parseFloat(money));
		tycoinEthLog.setNewNum(newMoney);
		tycoinEthLog.setFromType(payMode+"充值积分");
		tycoinEthLog.setActDate(DateUtils.getSystemTimeYMDByDate());
		tycoinEthLog.setRemark("");
		tycoinEthLog.setAddtime(System.currentTimeMillis());
		tycoinEthLog.setAddip("127.0.0.1");
		System.out.println("老的余额："+(Float.parseFloat(oldMoney)));
		System.out.println("充值金额："+(Float.parseFloat(money)));
		System.out.println("新的余额："+newMoney);
		tycoinEthLogRepository.save(tycoinEthLog);

	}

	 
	public boolean rechargeRollCallbackProcess(TycoinAccountRecharge tycoinAccountRecharge, HttpServletRequest request,
			HttpServletResponse response) {

		String userId = String.valueOf(tycoinAccountRecharge.getUserId());
		String money = "-" + tycoinAccountRecharge.getMoneyfloat() + "";
		int pay_mode = tycoinAccountRecharge.getPayMode();
		String payMode = "";
		String result = "";
		Map<String, String> resultMap = new HashMap<String, String>();
		boolean boo = true;
		System.out.println("pay_mode:"+pay_mode);
		if (pay_mode == 1) {
			payMode = "微信支付";
 			try {
				
		 		RefundReqData reverseReqData=new RefundReqData(tycoinAccountRecharge.getShopTradeNo(),tycoinAccountRecharge.getPaymentId(),tycoinAccountRecharge.getPaymentId()+"0000",Integer.valueOf(tycoinAccountRecharge.getMoney()),Integer.valueOf(tycoinAccountRecharge.getMoney()));

				result = WXPay.requestRefundService(reverseReqData);
                System.out.println("result为：result_code:"+result);
				resultMap = XMLUtils.getResult(result);
				result = JSONObject.fromObject(resultMap).toString();
				String result_code = resultMap.get("result_code");
				String return_code = resultMap.get("return_code");
                    System.out.println("退款的结果为：result_code:"+result_code+",return_code:"+return_code);
				if ("SUCCESS".equals(result_code) && "SUCCESS".equals(return_code)) {
					boo = true;
				} else {
					boo = false;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (pay_mode == 2) {
			payMode = "支付宝";
			ALIPayScan aLIPayScann = new ALIPayScan();
			result = aLIPayScann.test_trade_refund(tycoinAccountRecharge.getPaymentId(),
					String.valueOf(tycoinAccountRecharge.getMoneyfloat()));
			tycoinAccountRecharge.setReturnText(result);
			JSONObject alipay_trade_pay_response = JSONObject.fromObject(result);
			
 			if ("10000".equals(alipay_trade_pay_response.getString("result_code"))) {
				boo = true;
			} else {
				boo = false;
			}
		} else if (pay_mode == 3) {
			payMode = "百度钱包";
			RefundServlet refundServlet = new RefundServlet();
 			try {
				result = refundServlet.doPost(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			resultMap = XMLUtils.getResult(result);
			result = JSONObject.fromObject(resultMap).toString();
			String ret_code = resultMap.get("ret_code");
			String cashback_amount = resultMap.get("cashback_amount");
			if ("0".equals(ret_code) && tycoinAccountRecharge.equals(cashback_amount)) {
				boo = true;
			} else {
				boo = false;
			}

		} else if (pay_mode == 4) {
			payMode = "QQ钱包";

			QQpayScann qQpayScann = new QQpayScann();
			try {
				resultMap = qQpayScann.qpayRefund(tycoinAccountRecharge.getPaymentId(),tycoinAccountRecharge.getMoney());
 				String result_code=resultMap.get("result_code");
				String return_code=resultMap.get("return_code");
				String retcode=resultMap.get("retcode");
				if("SUCCESS".equals(return_code)&&"SUCCESS".equals(result_code)&&"0".equals(retcode)){
					boo = true;
				}else{
					boo = false;
				}
			} catch (Exception e) {
 				 e.printStackTrace();
			}

		} else if (pay_mode == 5) {
			payMode = "京东支付";
		} else if (pay_mode == 6) {
			payMode = "银联支付";
		}
		System.out.println("boo:为："+boo);
 		 if(boo){
		    boo=this.tycoinAccountRechargeCallBackSaveOrUpdate(tycoinAccountRecharge, request, response);
		 } 
 		System.out.println("boo:为："+boo);
             return boo;
	}
	
 
	public boolean tycoinAccountRechargeCallBackSaveOrUpdate(TycoinAccountRecharge tycoinAccountRecharge,
			HttpServletRequest request, HttpServletResponse response) {
		String userId = String.valueOf(tycoinAccountRecharge.getUserId());
		String money = tycoinAccountRecharge.getMoneyfloat() + "";
		int pay_mode = tycoinAccountRecharge.getPayMode();
		String payMode = "";
		String result = "";
		// 添加充值资金
		// --查询账户
		TycoinAccount outAccount = tycoinAccountRepository.findOneByuserId( userId);
		String oldMoney = String.valueOf(outAccount.getUseBtc());
 		
		outAccount.setUseMoney(new BigDecimal(oldMoney));
		tycoinAccountRepository.save(outAccount);
		// 1.添加打款方账积分账户日志记录
		TycoinAccountLog tycoinAccountLog = tycoinAccountLogRepository.findOneBylogno(tycoinAccountRecharge.getLogno());
		tycoinAccountLog.setStatus(3);
		tycoinAccountLog.setRemark(tycoinAccountLog.getRemark()+"-->已退款");
		tycoinAccountLogRepository.save(tycoinAccountLog);

		// 2.退款记录插入
		TycoinEthLog tycoinEthLog = new TycoinEthLog();
		tycoinEthLog.setUserId(String.valueOf(userId));
		tycoinEthLog.setOldNum(Float.parseFloat(oldMoney));
		tycoinEthLog.setNum(Float.parseFloat(money));
		tycoinEthLog.setNewNum((AmountUtil.sub(oldMoney, money).floatValue()));
		tycoinEthLog.setFromType("退款");
		tycoinEthLog.setActDate(DateUtils.getSystemTimeYMDByDate());
		tycoinEthLog.setRemark("");
		tycoinEthLog.setAddtime(System.currentTimeMillis());
		tycoinEthLog.setAddip("127.0.0.1");
		tycoinEthLogRepository.save(tycoinEthLog);

		tycoinAccountRecharge.setPaymentStatus(4);
		tycoinAccountRechargeService.save(tycoinAccountRecharge);
 		return true;
	}

}
